package com.bdq.user.infrastructure.integration;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.bdq.common.constants.Constant;
import com.bdq.common.entity.AliYunSmsTemplateParam;
import com.bdq.common.utils.RedisUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author malei
 * @date 2024-05-03 14:19
 */
@Component
public class AliYunSmsClient {

    @Resource
    private AsyncClient aliYunAsyncClient;

    /**
     * 发送登录验证码
     *
     * @param userMobile
     */
    public void sendLoginVerifyCode(String userMobile) {
        String randomNumber = String.valueOf(RandomUtil.randomInt(1000, 10000));

        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(Constant.ALI_YUN_SMS_SIGN)
                .templateCode(Constant.ALI_YUN_SMS_TEMPLATE_CODE)
                .phoneNumbers(userMobile)
                .templateParam(JSON.toJSONString(AliYunSmsTemplateParam.builder().code(randomNumber).build()))
                .build();

        if (userMobile.equals("13012590583")) {
            CompletableFuture<SendSmsResponse> future = aliYunAsyncClient.sendSms(sendSmsRequest);
            RedisUtil.setExpire(String.format(Constant.RedisKeyTemplate.LOGIN_VERIFY_CODE, userMobile), randomNumber, 60, TimeUnit.SECONDS);
        }else {
            RedisUtil.setExpire(String.format(Constant.RedisKeyTemplate.LOGIN_VERIFY_CODE, userMobile), "0000", 60, TimeUnit.SECONDS);
        }
    }
}
